<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/18
 * Time: 14:31
 */
namespace app\index\controller;
use app\index\model\Tyre;
use think\Request;
use app\index\model\Member as MemberModel;
use think\Exception;
use think\Cache;
use think\Loader;
use think\Db;
use think\View;

class Member
{
    /**
     * 会员登录
     * @return array
     * @throws Exception
     */
    public function login()
    {
        $username = Request::instance()->param('username');
        $password =Request::instance()->param('password');
        if (empty($username)) throw new Exception('username not Empty');
        if (empty($password)) throw new Exception('password not Empty');
        $model = new MemberModel();
        // 验证数据

        $user_id = $model->where(['username' => $username, 'password' => sha1($password)])->value('id');
        if ($user_id) {
            return ['code' => 200, 'message' => '登录成功', 'data' => ['user_id' => $user_id]];
        }
        return ['code' => 401, 'message' => '账号或密码错误'];

    }

    /**
     * 会员邀请码
     */
    public function qrcode($member_id)
    {
        $url = Request::instance()->domain()."/index.php/mobile/user_port/login?uid=".$member_id;
        Loader::import('phpqrcode.phpqrcode', EXTEND_PATH);
        $object = new \QRcode();
        $path = ROOT_PATH . 'public/index/member/' . $member_id . '.png';
        //第二个参数false的意思是不生成图片文件，如果你写上‘picture.png’则会在根目录下生成一个png格式的图片文件
        $data = Db::name('member_distribution md')
            ->where('hierarchy','like','%,'.$member_id.',%')
            ->field('m.username,md.create_time')
            ->join('member m','md.referrals_id = m.id')
            ->select()->toArray();
        foreach ($data as $k => &$v){
            //$v['username'] = hideStr($v['username'],3,4);
            $v['username'] = hideStr($v['username'],3,4);
        }
        $ret = $object->png($url, $path, 10, 10, 2);
        return view('',['member_id' => $member_id,'data' => $data]);
    }

    public function choose_system()
    {
        $view = new View();
        echo $view->fetch('');
    }


    /**
     * 会员注册
     */
    public function register(){
        try {
            $param = Request::instance()->param();
            $smsVerify = Cache::get('sms_verify_reg_' . $param['username']);

            $validate = Loader::validate('Member');

            if (!$validate->check($param)) return ['code' => 400, 'message' => $validate->getError()];
            if ($smsVerify != $param['code']) {
               return ['code' => 401, 'message' => '验证码错误'];
            }

            $model = new MemberModel();

            $model->create_time = date('Y-m-d H:i:s', time());
            $model->password = sha1($param['password']);
            $model->username = $param['username'];

            $result = $model->validate(true)->save();
            if ($result) {
                Db::name('member_distribution')->insert(['distribution_id' => '0', 'referrals_id' => $model->id, 'hierarchy' => '0,', 'level' => '1', 'create_time' => date('Y-m-d H:i:s', time())]);

                return ['code' => 200, 'message' => '注册成功', 'data' => ['user_id' => $model->id]];
            }
            return ['code' => 400, 'message' => '登录失败'];
        } catch (\Exception $e) {
            return ['m' =>$e->getMessage(),'l' => $e->getLine()];
        }
    }

    /**
     * 短信验证码
     * @return array
     */
    public function get_code()
    {

        //if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        $phone = Request::instance()->param('phone');
        $type = Request::instance()->param('type');
        $user_id = MemberModel::where(['username' => $phone])->value('id');

        if ($type == 'reg' && !empty($user_id)) {
            $find = Db::name('member')->where('username',$phone)->find();
            if(empty($find))  return ['code' => 402, 'message' => '用户未注册'];
            // 注册获取验证码
            return ['code' => 402, 'message' => '用户已注册'];

        } elseif ($type == 'find' && empty($user_id)) {
            $find = Db::name('member')->where('username',$phone)->find();
            if(empty($find))  return ['code' => 402, 'message' => '用户未注册'];
            // 找回密码获取验证码
            return ['code' => 402, 'message' => '用户未注册'];

        } elseif ($type == 'update' && empty($user_id)) {
            $find = Db::name('member')->where('username',$phone)->find();
            if(empty($find))  return ['code' => 402, 'message' => '用户未注册'];
            // 修改密码
            return ['code' => 402, 'message' => '用户未注册'];
        }elseif($type == 'forget'){
            $find = Db::name('member')->where('username',$phone)->find();
            if(empty($find))  return ['code' => 402, 'message' => '用户未注册'];
        }

        $smsVerify = Cache::get('sms_verify_' . $type . '_time_' . $phone);

        if (!empty($smsVerify)) {
            return ['code' => 401, 'message' => '60s内只能发送一次'];
        }

        $code = rand(100000, 999999);

        $content = '您好,您的短信验证码为：' . $code;
        $result = sendSMS($phone, $code);
        if ($result) {
            Cache::set('sms_verify_' . $type . '_time_' . $phone, $code, 60); // 短信请求有效期
            Cache::set('sms_verify_' . $type . '_' . $phone, $code, 3600);     // 短信保存有效期
            return ['code' => 200, 'message' => '发送成功', 'data' => ['code' => $code, 'phone' => $phone]];
        }
    }


    public function my($member_id)
    {
        $data = Db::name('member')->where('id', $member_id)->find();
        $order_no_pay_23 = Db::name('order')->where('member_id', $member_id)->where('status', 1)->where('order_type','in','2,3')->count();//未支付 代付款
        $order_no_pay_1  = Db::name('order')->where('member_id', $member_id)->where('status','in','1')->count();//未支付 代付款
        $order_no_pay = $order_no_pay_1;
        $order_pay = Db::name('order')->where('member_id', $member_id)->where('status', 'in','2,3')->count();//待收货
        $order_evaluate = Db::name('order')->where('member_id', $member_id)->where('status', 5)->count();//带评价
        $order_refund = Db::name('order')->where('member_id', $member_id)->where('status', 'in','10')->count();//退款中
        $order6 = Db::name('order')->where('member_id', $member_id)->where('status', 6)->count();//进行中 礼包6和服务6
        return ['code' => 200, 'message' => '会员中心', 'data' => $data, 'order_no_pay' => $order_no_pay, 'order_pay' => $order_pay, 'order_evaluate' => $order_evaluate, 'order_refund' => $order_refund,'order_service_6' => $order6];
    }

    /**
     * 单一字段值设置
     * @param $member_id
     * @param $field
     * @param $value
     * @return array
     */
    public function setfield($member_id,$field,$value)
    {
        $ret = Db::name('member')->where('id', $member_id)->setField($field, $value);
        if ($ret != false) {
            return ['code' => 200, 'message' => '设置成功'];
        }
        return ['code' => 400, 'message' => '名称设置'];
    }

    /**实名认证
     * @param $member_id
     * @param $real_name
     * @param $id_number
     * @return array
     */
    public function certification($member_id,$real_name,$id_number,$phone, $car_number, $car_model, $id_code, $test_time, $destory_time, $car_name = '', $engine_number, $brand_number, $register_time,$car_business_time = '')
    {

        $id_face = uploadImg('id_face');
        $id_back = uploadImg('id_back');
        $car_face = uploadOne('car_face');
        $car_back = uploadOne('car_back');
        if(empty($member_id) || empty($real_name) || empty($id_number)){
            return ['code' => 400,'message' => '字段不能为空'];
        }
        $ret = Db::name('member')->where('id',$member_id)->update([
            'real_name' => $real_name,
            'id_number' => $id_number,
            'id_face' => $id_face,
            'id_back' => $id_back,
            'is_certification' => 3,
            'phone' => $phone,
            'car_name' => $real_name,
            'engine_number' => $engine_number,
            'brand_number' => $brand_number,
            'register_time' => $register_time,
            'car_number' => $car_number,
            'car_model' => $car_model,
            'car_face' => $car_face,
            'car_back' => $car_back,
            'id_code' => $id_code,
            'test_time' => $test_time,
            'car_business_time' => $car_business_time,
            'destory_time' => $destory_time,
            'car_create_time' => date('Y-m-d H:i:s'),
        ]);
        if($ret){
          return ['code' => 200,'message' => '资料提交成功,等待审核'];
        }
        return ['code' => 400,'message' => '失败'];
    }



    /**头像修改
     * @param $member_id
     * @return array
     */
    public function head_pic($member_id)
    {
        $head_pic = uploadImg('head_pic');
        if (empty($head_pic)) return ['code' => 400, 'message' => '图片失败了'];
        $ret = Db::name('member')->where('id', $member_id)->setField(['avatar' => $head_pic]);
        if ($ret) {
            return ['code' => 200, 'message' => '头像上传成功', 'head_pic' => $head_pic];
        }
        return ['code' => 400, 'message' => '失败'];
    }

    /**
     * 忘记密码/修改密码
     * @param $username
     * @param $code
     * @param $password
     * @param $confirm_password
     * @return array
     */
    public function update_password($username, $code, $password, $confirm_password)
    {
        $sql_user = Db::name('member')->where('username', $username)->find();
        if (empty($sql_user)) return ['code' => 400, 'message' => '此用户不存在'];
        $cache_code = Cache::get('sms_verify_' . 'update' . '_' . $username);     // 短信保存有效期
        if ($cache_code != $code) {
            return ['code' => 400, 'message' => '验证码不正确'];
        }
        if ($password != $confirm_password) {
            return ['code' => 400, 'message' => '两次密码不一致'];
        }
        $ret = Db::name('member')->where('username|id', $username)->setField('password', sha1($password));
        if ($ret) {
            return ['code' => 200, 'message' => '密码修改成功'];
        }
        return ['code' => 400, 'message' => '失败'];
    }

    /**
     * @param $order_id
     * @return array
     * 确认取走轮胎
     */
    public function take_tyre($order_id,$member_id)
    {
        $status = Db::name('order')->where('id', $order_id)->where('member_id',$member_id)->value('status');
        if($status == 1){
            return ['code' => 400, 'message' => '此订单还没有支付'];
        }
        $ret = Db::name('order')->where('id', $order_id)->where('member_id',$member_id)->setField('take_tyre',2);
        if($ret !== false){
            return ['code' => 200, 'message' => '轮胎已确认取走'];
        }
        return ['code' => 400, 'message' => '失败'];
    }

    /**
     *
     * 保单
     */
    public function protect_order(){
        $param = Request::instance()->param();
        $ret = Db::name('protect_order')->where('member_id',$param['member_id'])->insert();
    }

    public function take(){
        if(strpos('5,4',5) !== false){
            echo 'hah';
        }
    }

    /**
     * @param $manage_io
     * 业务员邀请id
     */


    /**
     * 轮胎寄存
     */
    public function tyre($member_id){
        //$username = Db::name('member')->where('id',$member_id)->value('username');
        $data = (new \app\console\model\Order())->where('member_id',$member_id)
            ->where('status','in','1,6,5,4')
            ->where('order_type',2)
            ->where('single_id',11)
            ->order('id','desc')
            ->field('id,amount price,order_number,start_time,end_time,multi_pic,explain,take_tyre')
            ->paginate(6)->each(function($item,$key){
            $item['multi_pic'] = unserialize($item['multi_pic']) ? unserialize($item['multi_pic']) : [];
            $item['remark'] = $item['explain'];
        });

        return ['code' => 200, 'message' => '轮胎寄存列表','data' => $data];
//        // 获取表单上传文件
//        $multi_pic = [];
//        $files = request()->file('image');
//        foreach($files as $file){
//            // 移动到框架应用根目录/public/uploads/ 目录下
//            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
//            if($info){
//            $multi_pic[] = $info->getFilename();
//                // 输出 42a79759f284b767dfcb2a0197904287.jpg
//            }else{
//                // 上传失败获取错误信息
//                return $file->getError();
//            }
//        }
//        $insert = ['member_id' => $member_id,'number' => $number,'remark' => $remark,'start_time' => $start_time,'end_time' => $end_time,'multi_pic' => json_encode($multi_pic)];
//
//        $ret = Db::name('tyre')->insertGetId($insert);
//        if($ret){
//            return ['code' => 200, 'message' => '提交成功','multi_pic' => $multi_pic];
//        }
//        return ['code' => 400, 'message' => '失败'];

    }
    public function tyre1($member_id){

        // 获取表单上传文件
        $multi_pic = [];
        $files = request()->file('image');
        foreach($files as $file){
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
            $multi_pic[] = $info->getFilename();
                // 输出 42a79759f284b767dfcb2a0197904287.jpg
            }else{
                // 上传失败获取错误信息
                return $file->getError();
            }
        }
        $insert = ['member_id' => $member_id,'number' => 1,'remark' => 2,'start_time' => 3,'end_time' => 4,'multi_pic' => serialize($multi_pic)];

        $ret = Db::name('tyre')->insertGetId($insert);
        if($ret){
            return ['code' => 200, 'message' => '提交成功','multi_pic' => $multi_pic];
        }
        return ['code' => 400, 'message' => '失败'];

    }

    /**
     * @param $member_id
     * @param $car_number
     * @param $car_model
     * @return array
     * 我的车库添加
     */
    public function my_car_create($id_number,$car_business_time,$phone, $member_id, $car_number, $car_model, $id_code, $test_time, $destory_time, $car_name, $engine_number, $brand_number, $register_time)
    {
        $car_face = uploadOne('car_face');
        $car_back = uploadOne('car_back');
        $id_face = uploadOne('id_face');
        $id_back = uploadOne('id_back');
        $username = Db::name('member')->where('id',$member_id)->value('username');
        $insert = [
            'username' => $username,
            'phone' => $phone,
            'car_name' => $car_name,
            'engine_number' => $engine_number,
            'brand_number' => $brand_number,
            'register_time' => $register_time,
            'member_id' => $member_id,
            'car_number' => $car_number,
            'car_model' => $car_model,
            'car_face' => $car_face,
            'car_back' => $car_back,
            'id_face' => $id_face,
            'id_back' => $id_back,
            'id_code' => $id_code,
            'id_number' => $id_number,
            'car_business_time' => $car_business_time,
            'test_time' => $test_time,
            'destory_time' => $destory_time,
            'create_time' => date('Y-m-d H:i:s'),
        ];
        $ret = Db::name('car')->insert($insert);
        if ($ret) {
            return ['code' => 200, 'message' => '添加成功', 'car_face' => $car_face, 'car_back' => $car_back, 'id_face' => $id_face, 'id_back' => $id_back];
        }
        return ['code' => 400, 'message' => '失败'];

    }


    public function my_car_update($id_number, $car_bussiness_time, $phone, $id, $member_id, $car_number, $car_model, $id_code, $test_time, $destory_time, $car_name, $engine_number, $brand_number, $register_time)
    {
        $car_face = uploadOne('car_face');
        $car_back = uploadOne('car_back');
        $id_face = uploadOne('id_face');
        $id_back = uploadOne('id_back');
        $insert = [
            'phone' => $phone,
            'car_name' => $car_name,
            'engine_number' => $engine_number,
            'brand_number' => $brand_number,
            'register_time' => $register_time,
            'id' => $id,
            'member_id' => $member_id,
            'car_number' => $car_number,
            'car_model' => $car_model,
            'car_face' => $car_face,
            'car_back' => $car_back,
            'id_face' => $id_face,
            'id_back' => $id_back,
            'id_number' => $id_number,
            'car_business_time' => $car_bussiness_time,
            'id_code' => $id_code,
            'test_time' => $test_time,
            'destory_time' => $destory_time,
        ];
        $ret = Db::name('car')->update($insert);
        if ($ret !== false) {
            return ['code' => 200, 'message' => '修改成功', 'car_face' => $car_face, 'car_back' => $car_back];
        }
        return ['code' => 400, 'message' => '失败'];

    }

    public function my_car_update1($id_number, $car_business_time, $phone, $id, $member_id, $car_number, $car_model, $id_code, $test_time, $destory_time, $car_name, $engine_number, $brand_number, $register_time)
    {
        $car_face_url = uploadOne1('car_face');
        $car_back_url = uploadOne1('car_back');
        $id_face_url = uploadOne1('id_face');
        $id_back_url = uploadOne1('id_back');
        $insert = [
            'phone' => $phone,
            'car_name' => $car_name,
            'engine_number' => $engine_number,
            'brand_number' => $brand_number,
            'register_time' => $register_time,
            'id' => $id,
            'member_id' => $member_id,
            'car_number' => $car_number,
            'car_model' => $car_model,
            'car_face' => $car_face_url,
            'car_back' => $car_back_url,
            'id_face' => $id_face_url,
            'id_back' => $id_back_url,
            'id_number' => $id_number,
            'car_business_time' => $car_business_time,
            'id_code' => $id_code,
            'test_time' => $test_time,
            'destory_time' => $destory_time,
        ];
        $ret = Db::name('car')->update($insert);
        if ($ret !== false) {
            return ['code' => 200, 'message' => '修改成功', 'car_face' => $car_face_url, 'car_back' => $car_back_url];
        }
        return ['code' => 400, 'message' => '失败'];

    }

    /**
     * @param $member_id
     * @return array
     * 车库列表
     */
    public function my_car_list($member_id)
    {
       $data = Db::name('car')->order('id','desc')->where('member_id',$member_id)->where('is_delete',0)->select();
       return ['code' => 200, 'message' => '我的车库','data' => $data];
    }

    public function my_car_destory($member_id, $id)
    {
        $ret = Db::name('car')->where('member_id', $member_id)->where('id', $id)->delete();
        if ($ret) {
            return ['code' => '200', 'message' => '删除成功'];
        }
        return ['code' => '400', '失败'];
    }
    /**
     * 我的车修改
     */

    public function my_car_updates($member_id,$id,$field,$value){
       $ret = Db::name('car')->where('id',$id)->where('member_id',$member_id)->setField($field,$value);
       if($ret){
           return ['code' => '200','message' => '修改成功'];
       }
        return ['code' => '400','失败'];
    }

    /**
     * @param $member_id
     * @param $id
     * @param $field
     * @return array
     * 我的车图片修改
     */
    public function my_car_pic($member_id,$id,$field)
    {
        $value = uploadOne('update_pic');
        $ret = Db::name('car')->where('id',$id)->where('member_id',$member_id)->setField($field,$value);
        if($ret){
            return ['code' => '200','message' => '修改成功',$field => $value];
        }
        return ['code' => '400','失败'];
    }


    /**
     * @param $member_id
     * @return array
     * 会员卡
     */
    public function card($member_id)
    {
        $data = Db::name('member_card')->alias('mc')
            ->join('member m','mc.member_id = m.id')
            ->whereTime('end_time','>',time())
            ->whereTime('start_time','<',time())
            ->where('mc.member_id',$member_id)
            ->where('type','gt',0)
            ->fetchSql(false)
            ->field('m.car_number,mc.id,mc.member_id,mc.content conetnt,mc.minus_count count,DATE_FORMAT(mc.start_time,"%Y.%m.%d") start_time,DATE_FORMAT(mc.end_time,"%Y.%m.%d") end_time,mc.type,mc.shop_id,mc.start_time create_time')
            ->select();
        return ['code' => 200, 'message' => '会员卡', 'data' => $data];
    }

    /**
     * @param $member_id
     * @return array
     * 会员卡消费记录w
     */
    public function card_records($id)
    {
        $data = Db::name('member_card_records')->where('is_agree',2)->where('card_id', $id)->field('DATE_FORMAT(create_time,"%Y.%m.%d") create_time,shop_title,service_content,card_id,card_type')->group('create_time')->paginate(10);
        return ['code' => 200, 'message' => '会员卡消费记录', 'data' => $data];
    }




}